﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using ACL.Comm;

namespace WcfService3
{
    //this will force the servcice to run as a singleton
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class AgentPoolService : IAgentPool
    {


        private List<Agent> Agents = new List<Agent>();

        private List<Message> Messages = new List<Message>();


        public AgentPoolService()
         {
             
             
         }


        #region
        //message
        public void Whisper(Message message)
        {
            message.hasMessageBeenRead = false;

            Messages.Add(message);
        }

        public void Shout(Message message)
        {
            foreach (var agent in Agents)
            {
                Messages.Add(new Message { body = message.body, recipeint = agent, sender = message.sender, subject = message.subject, hasMessageBeenRead = false });
            }
            
        }

        
        public List<Message> GetUnReadMessages(Agent agent)
        {
            return Messages.Where(b => b.sender.Id == agent.Id && b.hasMessageBeenRead == false).ToList(); 
        
        }

        public List<Message> GetAllReadMessages(Agent agent)
        {
            return Messages.Where(b => b.sender.Id == agent.Id && b.hasMessageBeenRead == true).ToList(); 
        
        }

        public List<Message> GetAllMessages(Agent agent)
        {
            return Messages.Where(b => b.sender.Id == agent.Id).ToList();

        }
        #endregion

        #region
        //connection

        public List<Agent> GetAgents()
        {
            return Agents;
        }

        /// <summary>
        /// NewId is assigned to ensure uniqueness
        /// </summary>
        /// <param name="agent"></param>
        /// <returns></returns>
        public Agent Subscribe(Agent agent)
        {
            agent.Id = Guid.NewGuid().ToString();

            if (!Agents.Contains(agent))
                Agents.Add(agent);
            
            //get the contract
            IContractCallBack icb = OperationContext.Current.GetCallbackChannel<IContractCallBack>();
            //uyse the callback
            icb.CallBackFUnction( string.Format("agent {0} joined", agent.Id));

            return agent;
           
        }

        public void UnSubscribe(Agent agent)
        {
            if (!Agents.Contains(agent))
                Agents.Remove(agent);
        }
       
        public void TearDownService()
        {   
            Agents.Clear();
            
        }

        #endregion
    }
}
